package uk.co.q3c.deplan.client.domain.resource;

import javax.persistence.Transient;

import uk.co.q3c.deplan.client.domain.DomainKind;
import uk.co.q3c.deplan.client.domain.util.CalendarAdjustments;
import uk.co.q3c.deplan.client.service.ServiceFactory;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.annotation.Cached;
import com.googlecode.objectify.annotation.Serialized;
import com.googlecode.objectify.annotation.Unindexed;

/**
 * @see BaseCalendar
 * @See IndividualResource
 * @author DSowerby 12 May 2008 23:27:55
 * 
 */
@Unindexed
@Cached(expirationSeconds = 600)
public class ResourceCalendar extends WorkingCalendar {

	private static final long serialVersionUID = 1L;

	@Serialized
	private CalendarAdjustments adjustments;

	private int resourceId;

	@Transient
	private BaseCalendar baseCalendar;

	private Key<? extends ResourceCalendar> key;

	protected ResourceCalendar() {
		super();
	}

	public ResourceCalendar(ServiceFactory connection) {
		super(connection);
	}

	@Override
	public String toString() {
		return "Resource Calendar";
	}

	public BaseCalendar getBaseCalendar() {
		if (baseCalendar == null) {
			baseCalendar = getConnection().calendarService()
					.findBaseCalendar();
		}
		return baseCalendar;
	}

	/**
	 * Sets the {@link #baseCalendar} and also sets the {@link #baseCalendarKey}
	 * 
	 * @param baseCalendar
	 */
	public void setBaseCalendar(BaseCalendar baseCalendar) {
		this.baseCalendar = baseCalendar;
	}

	public int getResourceId() {
		return resourceId;
	}

	public void setResourceId(int resourceId) {
		this.resourceId = resourceId;
	}

	/**
	 * @see uk.co.q3c.deplan.client.domain.resource.WorkingCalendar#createAdjustments()
	 */
	@Override
	protected void createAdjustments() {
		adjustments = new CalendarAdjustments(getConnection());

	}

	/**
	 * @see uk.co.q3c.deplan.client.domain.resource.WorkingCalendar#getAdjustments()
	 */
	@Override
	public CalendarAdjustments getAdjustments() {
		return adjustments;
	}

	/**
	 * @see uk.co.q3c.deplan.client.domain.resource.WorkingCalendar#getBaseWorkingTime()
	 */
	@Override
	public WorkingTime getBaseWorkingTime() {
		return getBaseCalendar();

	}

	@Override
	public void afterLoad(ServiceFactory connection) {
		super.afterLoad(connection);
		if (adjustments == null) {
			adjustments = new CalendarAdjustments(getConnection());
		}

	}

	@Override
	public DomainKind getKind() {
		return DomainKind.ResourceCalendar;
	}

	@Override
	public Key<? extends ResourceCalendar> getKey() throws PersistenceReferenceException {
		if (getKeyId() == null) {
			throw new PersistenceReferenceException(this.getName() + " has not been saved and cannot therefore be used as a reference");
		}
		if (key == null) {
			key = connection.resourceService()
					.keyFor(this);
		}
		return key;
	}

	@Override
	public void setKeyId(Long keyId) {
		throw new RuntimeException("Not yet implemented");
	}

}
